package com.oocl.o2o.merchant.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.oocl.o2o.connectutil.dto.AdvertFeedbackToMDTO;
import com.oocl.o2o.connectutil.dto.AdvertisementDTO;
import com.oocl.o2o.connectutil.util.AdvertForMUtil;
import com.oocl.o2o.merchant.dao.AdvertisementDao;
import com.oocl.o2o.merchant.dao.FoodDao;
import com.oocl.o2o.merchant.dao.MerchantDao;
import com.oocl.o2o.merchant.entity.Advertisement;
import com.oocl.o2o.merchant.entity.AdvertisementStatus;
import com.oocl.o2o.merchant.entity.Food;
import com.oocl.o2o.merchant.entity.Merchant;
import com.oocl.o2o.merchant.service.AdvertisementManager;
import static com.oocl.o2o.merchant.util.ImageUtil.*;

@Service
public class AdvertisementManagerImpl implements AdvertisementManager {
	@Autowired
	private AdvertisementDao advertisementDao;
	@Autowired
	private MerchantDao merchantDao;
	@Autowired
	private FoodDao foodDao;

	@Transactional
	@Override
	public Advertisement sendAdvertisement(Advertisement ad,String applyReason) {
		String merchantId = ad.getMerchant().getId();
		String foodId = ad.getFood().getId();
		Merchant merchant = merchantDao.findById(merchantId);
		Food food = foodDao.findById(foodId);
		ad = advertisementDao.add(ad);
		if (ad == null)
			return null;
		String advertId = ad.getId();
		String merchantName = merchant.getUsername();
		String foodName = food.getName();
		Double foodPrice = food.getPrice();
		String foodImage = loadPic(getAbsolutePath(food.getImage()));
		Double tenderPrice = ad.getCompPrice();
		String foodType = food.getFoodType().getTypeName();
		AdvertisementDTO adDTO = new AdvertisementDTO(advertId, merchantName, foodName, foodPrice, foodImage,
				tenderPrice, foodType, applyReason);
		if (!AdvertForMUtil.send(adDTO)) {
			advertisementDao.delete(ad.getId());
			return null;
		}
		return ad;
	}

	@Transactional
	@Override
	public List<Advertisement> findByMerchantId(String merchantId) {
		Merchant merchant = merchantDao.findById(merchantId);
		// no this merchant
		if (merchant == null) {
			return null;
		}
		List<Advertisement> advertisements = merchant.getAdvertisements();
		advertisements.size(); // trigger fetch
		return advertisements;
	}

	@Transactional
	@Override
	public Advertisement receiveFeedBack(AdvertFeedbackToMDTO feedback) {
		Advertisement ad = advertisementDao.findById(feedback.getAdvertId());
		if (ad == null) {
			System.out.println("adListener... don't exit this ad");
			return null;
		}
		switch (feedback.getStatus()) {
		case OPEN:
			System.out.println("setOn");
			ad.setAdvertisementStatus(AdvertisementStatus.ON);
			break;
		case OFF:
			ad.setAdvertisementStatus(AdvertisementStatus.OFF);
			break;
		}
		return ad;
	}
}
